# coding=utf-8
import json
import uuid

from django.db.models import Q

from common.log import logger
from components.bk.apis.bk_login.get_all_user import GetAllUser
from components.bk.apis.bk_login.get_batch_user import GetBatchUser
from components.bk.apis.bk_login.get_batch_user_platform_role import GetBatchUserPlatformRole
from components.bk.apis.bk_login.get_user import GetUser
# from components.bk.apisv2.usermanage.get_batch_users import GetBatchUsers
from components.bk.apisv2.usermanage.retrieve_user import RetrieveUser
from components.bk.apisv2.usermanage.usermanage_component import UsermanageComponent
from components.generic.templates.cmsi.toolkit.tools import get_user_contact
from esb.bkauth.models import BKUser

from esb.bkauth.validators import UserAuthValidator
from esb.bkcore.models import ESBChannel
from esb.component import get_components_manager, CompRequest


def get_qy_wx_user(user_id):
    """
    根据微信Id获取企业微信用户
    :param user_id:、

    :return:
    """
    components_manager = get_components_manager()
    comp_class = components_manager.get_comp_by_name('generic.weixin_qy.get_user')
    comp_obj = comp_class()
    channel = ESBChannel.objects.filter(path='/cmsi/send_weixin/').first()
    comp_conf = json.loads(channel.comp_conf)
    if isinstance(comp_conf, (tuple, list)):
        comp_conf = dict(comp_conf)
    kwargs = dict({
        'corpid': comp_conf.get('wx_qy_corpid'),
        'corpsecret': comp_conf.get('wx_qy_corpsecret'),
        'userid': user_id,
    })
    comp_obj.set_request(
        CompRequest(
            input=kwargs
        )
    )
    return comp_obj.invoke()


def validate_user_auth(request):
    """
    验证用户权限
    :param request:
    :return: None
    """
    request.g.authorization = {'bk_token': request.COOKIES.get('bk_token')}
    request.g.kwargs = {'bk_token': request.COOKIES.get('bk_token')}
    if not request.g.get('app_code'):
        request.g.app_code = request.g.kwargs.get('bk_app_code') or request.g.kwargs.get('app_code', '')
    request.g.request_id = uuid.uuid4().get_hex()
    UserAuthValidator().validate(request)


def calc_page(request):
    """
    计算分页
    :param request: page-第几页(默认：1)，pagesize-一页几条（默认：10）
    :return: 切片start,end(默认1,10)
    """
    query_params = request.GET.copy()
    page = int(query_params.pop('page', [1])[0])
    pagesize = int(query_params.pop('pagesize', [10])[0])
    start = (page - 1) * pagesize
    end = page * pagesize
    return start, end


def get_filters(request):
    """
    根据请求参数创建Filters
    :param request:
    :return: {'is_close': 1}
    """
    query_params = request.GET.copy()
    pops = ['page', 'pagesize', 'bk_token', 'search', 'group_by']
    for key in pops:
        query_params.pop(key, None)
    logger.info(query_params)
    return {k: v for k, v in query_params.items()}


def filter_by_user(queryset, request):
    user = GetUser().invoke({'bk_token': request.g.kwargs.get('bk_token')})
    # 不是超管用户
    # # if user.get('data', {}).get('role') != '1':
    username = user.get('data', {}).get('username', '')
    users = RetrieveUser(current_user=BKUser(username)).invoke(
        {
            'app_code': 'esb',
            'bk_token': request.g.kwargs.get('bk_token'),
            'id': username, 'fields': 'id,username'
        })
    user_id = users.get('data', {}).get('id', '')
    if not user_id:
        queryset = queryset.none()
    else:
        # wx_user = get_qy_wx_user(wx_user_id)
        # if wx_user.get('result'):
        queryset = queryset.filter(receivers=user_id)
        # else:
        #     queryset = queryset.filter(receivers=wx_user_id)
    return queryset
